/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JPanelManualUpload.java
 *
 * Created on Feb 22, 2011, 3:09:45 PM
 */

package com.wisc.csvParser.plugins;

import com.wisc.csvParser.plugins.DataParserManualUpload.events;
import org.jdom.input.SAXBuilder;
import org.jdom.*;
import java.awt.FileDialog;
import javax.swing.*;
import com.wisc.csvParser.*;
import com.wisc.configFileConverter.ConfigFile;
import java.awt.Color;
import java.util.ArrayList;
import java.awt.Component;
import java.io.File;
import java.io.DataInputStream;
import java.io.FileInputStream;

/**
 *
 * @author glocke-ou
 */
public class JPanelManualUpload extends javax.swing.JPanel {

    DataParserManualUpload parser;
    //File fileOpened;
    //A list of the components that need to have enable toggled when parsing
    private ArrayList<Component> components = new ArrayList<Component>();

    /** Creates new form JPanelManualUpload */
    public JPanelManualUpload(DataParserManualUpload p) {
        initComponents();
        parser = p;
        components.add(monitoredFileList);
        components.add(jProgressBar1);
        components.add(removeConfigButton);
        components.add(editConfigButton);

        parser.addEventHandler(new DataParserManualUpload.ManualUploadEventHandler() {

            @Override
            public void eventRaised(events v) {
                newEvent(v);
            }
        });

        jProgressBar1.setVisible(false);
        this.updateDisplay();
    }

     /** Creates new form JPanelManualUpload
     * Shows an alert message to the user. Used by the underlying object
     * to notify the user of important exceptions.
     *
     * @param message Message to be show to the user by this swing object.
     */
    public void showMessageDialog(String message) {
        JOptionPane.showMessageDialog(
                (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, this), message);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        editConfigButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jProgressBar1 = new javax.swing.JProgressBar();
        removeConfigButton = new javax.swing.JButton();
        rowsParsedLabel = new javax.swing.JLabel();
        malformedRowsLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        monitoredFileList = new javax.swing.JList();
        addConfigButton = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        confirmLabel = new javax.swing.JLabel();

        jLabel1.setText("One-off parse of a configuration");

        jLabel2.setText("Config to Parse:");

        editConfigButton.setText("Edit Config");
        editConfigButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editConfigButtonActionPerformed(evt);
            }
        });

        jLabel3.setText("File Parsing:");

        jProgressBar1.setBackground(new java.awt.Color(255, 255, 255));

        removeConfigButton.setText("Remove Config");
        removeConfigButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeConfigButtonActionPerformed(evt);
            }
        });

        rowsParsedLabel.setText("Rows Parsed: ");

        malformedRowsLabel.setText("Malformed Rows: ");

        monitoredFileList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                monitoredFileListMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(monitoredFileList);

        addConfigButton.setText("Add Config");
        addConfigButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addConfigButtonActionPerformed(evt);
            }
        });

        confirmLabel.setText("All files parsed!");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING))
                        .addContainerGap(292, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(rowsParsedLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)
                        .addGap(367, 367, 367))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(malformedRowsLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
                        .addGap(350, 350, 350))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(4, 4, 4)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(confirmLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 92, Short.MAX_VALUE))
                                    .addComponent(jLabel4)))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(addConfigButton)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(editConfigButton)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(removeConfigButton))))
                        .addGap(161, 161, 161))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addConfigButton)
                    .addComponent(editConfigButton)
                    .addComponent(removeConfigButton))
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(confirmLabel)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(rowsParsedLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(malformedRowsLabel)
                .addGap(35, 35, 35))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void removeConfigButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeConfigButtonActionPerformed
        if(monitoredFileList.getSelectedIndex() != -1){
            if(JOptionPane.showConfirmDialog(null,
                    "Are you sure you want to remove this config?")!=JOptionPane.OK_OPTION)
                return;

            int index = monitoredFileList.getSelectedIndex();
            parser.removeMonitoredFile(index);
            parser.removeConfigName(index);
            updateDisplay();
        }
    }//GEN-LAST:event_removeConfigButtonActionPerformed


    private void editConfigButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editConfigButtonActionPerformed
        if(!parser.isStarted() && monitoredFileList.getSelectedIndex() != -1){
            JDialogManualUpload editDialog =
                    new JDialogManualUpload(this,parser.getMonitoredFile(monitoredFileList.getSelectedIndex())
                    , parser.getMonitoredFile(monitoredFileList.getSelectedIndex()).getConfigName()
                    , parser);

            editDialog.setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE );
            editDialog.pack();
            editDialog.setLocationRelativeTo(this);
            editDialog.setVisible(true);

            updateDisplay();
        }
    }//GEN-LAST:event_editConfigButtonActionPerformed

    private void addConfigButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addConfigButtonActionPerformed
        DataParserManualUpload.TableBasedFile file = parser.getNewFileObject();        
        String configName = "Unnamed Config";

        JDialogManualUpload editDialog =
                new JDialogManualUpload(this,file,configName,parser);
        editDialog.setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE );
        editDialog.pack();
        editDialog.setLocationRelativeTo(this);
        editDialog.setVisible(true);

        updateDisplay();
    }//GEN-LAST:event_addConfigButtonActionPerformed

    private void monitoredFileListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_monitoredFileListMouseClicked
        if(evt.getClickCount()==2 && !parser.isStarted()){
            JDialogManualUpload editDialog =
                    new JDialogManualUpload(this,parser.getMonitoredFile(monitoredFileList.getSelectedIndex())
                    , parser.getMonitoredFile(monitoredFileList.getSelectedIndex()).getConfigName()
                    , parser);

            editDialog.setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE );
            editDialog.pack();
            editDialog.setLocationRelativeTo(this);
            editDialog.setVisible(true);

            updateDisplay();
        }
    }//GEN-LAST:event_monitoredFileListMouseClicked

    private void updateDisplay() {
        monitoredFileList.setListData(parser.getConfigNames());

        confirmLabel.setText("Waiting for start...");
        confirmLabel.setForeground(Color.red);
        
        confirmLabel.setVisible(true);
        //updates progress bar
        //jProgressBar1.setVisible(false); // FOR TESTING
        //jProgressBar1.setIndeterminate(parser.isStarted());
        //enables and disables components depending on state.
        for (Component c:components) {
            c.setEnabled(!parser.isStarted());
        }
    }

     /**
     * Handles different events raised by underlying parser object.
     * Mostly pertaining to update of GUI.
     * @param e
     */
    public void newEvent(DataParserManualUpload.events e) {
        if (e == DataParserManualUpload.events.startDataParse) {
            confirmLabel.setVisible(false);
            jProgressBar1.setVisible(true);
            jProgressBar1.setIndeterminate(true);
        } else if (e == DataParserManualUpload.events.reconfigured ||
                e == DataParserManualUpload.events.stopped) {
            jProgressBar1.setVisible(false);
            confirmLabel.setVisible(true);
            updateDisplay();
        } else if (e == DataParserManualUpload.events.newMalformedRow) {
            malformedRowsLabel.setText("Malformed Rows: " +
                    Integer.toString(parser.getMalformedRows().size()));
        } else if (e == DataParserManualUpload.events.rowParsed) {
            rowsParsedLabel.setText("Rows Parsed: " +
                    Long.toString(parser.getRowsParsedTotal()));
        } else if (e == DataParserManualUpload.events.finishDataParse) {
            jProgressBar1.setVisible(false);
            confirmLabel.setText("All files parsed! Click Stop to reset.");
            confirmLabel.setForeground(new Color(0,128,0));
            confirmLabel.setVisible(true);
        } else if (e == DataParserManualUpload.events.error) {
            jProgressBar1.setVisible(false);
            confirmLabel.setText("Error occured. Click Stop to reset.");
            confirmLabel.setForeground(Color.red);
            confirmLabel.setVisible(true);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addConfigButton;
    private javax.swing.JLabel confirmLabel;
    private javax.swing.JButton editConfigButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel malformedRowsLabel;
    private javax.swing.JList monitoredFileList;
    private javax.swing.JButton removeConfigButton;
    private javax.swing.JLabel rowsParsedLabel;
    // End of variables declaration//GEN-END:variables

}
